package com.mzy.leetcode;

import com.mzy.ListNode;

import java.util.concurrent.CompletableFuture;

public class ReverseKGroup {

    public static class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {

            ListNode start = head;
            ListNode end = getGroupEnd(start, k);
            if(end == null) return head;

            head = end;
            reverse(start, end);
            ListNode lastEnd = start;
            while (lastEnd.next != null) {
                start = lastEnd.next;
                end = getGroupEnd(start, k);
                if(end == null) return head;

                reverse(start, end);

                lastEnd.next = end;
                lastEnd = start;

            }

            return head;
        }


        public void reverse(ListNode start, ListNode end) {
            end = end.next;

            ListNode pre = null;
            ListNode next = null;
            ListNode cur = start;
            while (cur != end) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            start.next = end;
        }

        public ListNode getGroupEnd(ListNode start, int k) {

            while (--k != 0 && start != null) {
                start = start.next;
            }
            return start;
        }
    }

    public static void main(String[] args) {

        Solution solution = new Solution();

        ListNode start = new ListNode(9);
        start.next = new ListNode(2);
    }
}
